package com.xja.seckill.gateway.loginFilter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

@Component

//登录验证
public class LoginFilter extends ZuulFilter {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String filterType() {//过滤类型
        return PRE_TYPE;  //前置过滤
    }

    @Override
    public int filterOrder() {//拦截器优先级
        return PRE_DECORATION_FILTER_ORDER-2;
    }

    @Override
    public boolean shouldFilter() {//是否开启过滤
        /*
        * 可跳过方法返回false
        * 需要拦截的返回true
        * */
        RequestContext requestContext = RequestContext.getCurrentContext ();
        HttpServletRequest request = requestContext.getRequest ();
        String username = request.getParameter ("username");
        if (request.getRequestURI ().contains ("/login") || request.getRequestURI ().contains ("/registered")){
            return false;
        }else if (redisTemplate.opsForValue ().get ("session-"+username)!=null){
            return false;
        }

//        HttpSession session = request.getSession ();
//        if (session.getAttribute ("username") == null) {
//            return true;
//        }
//        //如果url中包含访问订单服务的操作拦截
//        if (request.getRequestURI ().indexOf ("/order/")!=-1){
//            return true;
//        }
//        Object o = redisTemplate.opsForValue ().get ("tokens" + username);
        return true;
    }

    @Override
    public Object run() throws ZuulException {//拦截操作
        RequestContext requestContext = RequestContext.getCurrentContext ();
        HttpServletRequest request = requestContext.getRequest ();
        Object o = request.getSession ().getAttribute ("username");
        if (o==null){
            System.out.println ("未登录");
            requestContext.setSendZuulResponse (false);
            requestContext.setResponseStatusCode (HttpStatus.SC_UNAUTHORIZED);
        }
        return null;
    }
}
